import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Form, 
  Input, 
  Select, 
  ColorPicker, 
  Slider, 
  Space,
  Typography,
  Row,
  Col,
  Card,
  Radio,
  Tabs
} from 'antd';
import { 
  NodeIndexOutlined, 
  AppstoreOutlined, 
  BgColorsOutlined, 
  HighlightOutlined,
  TagsOutlined
} from '@ant-design/icons';
import { getGraphTypeStyle } from '../../styles/graphThemes';

const { Option } = Select;
const { TextArea } = Input;
const { Text } = Typography;
const { TabPane } = Tabs;

/**
 * 节点编辑器组件
 * 支持不同图谱类型的节点样式编辑
 */
const NodeEditor = ({ 
  visible, 
  onCancel, 
  onSave, 
  nodeData, 
  mode = 'add',
  nodeTypeOptions = [],
  graphType = 'knowledge' // 添加图谱类型参数
}) => {
  const [form] = Form.useForm();
  const [nodeColor, setNodeColor] = useState('#1677ff');
  const [nodeSize, setNodeSize] = useState(20);
  const [nodeShape, setNodeShape] = useState('circle');
  const [activeTab, setActiveTab] = useState('basic');
  
  // 获取当前图谱类型的样式配置
  const graphStyle = getGraphTypeStyle(graphType);

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && nodeData) {
        form.setFieldsValue({
          label: nodeData.label,
          type: nodeData.type,
          description: nodeData.description || '',
          category: nodeData.category || '',
          properties: nodeData.properties || {}
        });
        setNodeColor(nodeData.color || graphStyle?.nodeColor?.({}) || '#1677ff');
        setNodeSize(nodeData.size || 20);
        setNodeShape(nodeData.shape || 'circle');
      } else {
        form.resetFields();
        setNodeColor(graphStyle?.nodeColor?.({}) || '#1677ff');
        setNodeSize(20);
        setNodeShape(graphStyle?.nodeShape || 'circle');
      }
    }
  }, [visible, mode, nodeData, form, graphStyle]);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const nodeInfo = {
        ...nodeData,
        ...values,
        color: nodeColor,
        size: nodeSize,
        shape: nodeShape
      };
      onSave(nodeInfo);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 根据图谱类型获取默认节点类型选项
  const getDefaultNodeTypes = () => {
    const typeMap = {
      'knowledge': [
        { label: '概念', value: 'concept' },
        { label: '实体', value: 'entity' },
        { label: '属性', value: 'attribute' }
      ],
      'mind': [
        { label: '中心主题', value: 'central' },
        { label: '主要主题', value: 'main' },
        { label: '子主题', value: 'sub' }
      ],
      'concept': [
        { label: '概念', value: 'concept' },
        { label: '关键词', value: 'keyword' },
        { label: '术语', value: 'term' }
      ],
      'social': [
        { label: '人物', value: 'person' },
        { label: '组织', value: 'organization' },
        { label: '角色', value: 'role' }
      ],
      'flow': [
        { label: '开始', value: 'start' },
        { label: '过程', value: 'process' },
        { label: '决策', value: 'decision' },
        { label: '结束', value: 'end' }
      ],
      'ontology': [
        { label: '类', value: 'class' },
        { label: '属性', value: 'property' },
        { label: '实例', value: 'individual' }
      ]
    };
    
    return typeMap[graphType] || [
      { label: '概念', value: 'concept' },
      { label: '实体', value: 'entity' },
      { label: '属性', value: 'attribute' },
      { label: '事件', value: 'event' },
      { label: '类别', value: 'category' }
    ];
  };

  // 获取可用的节点形状选项
  const getShapeOptions = () => {
    const commonShapes = [
      { label: '圆形', value: 'circle' },
      { label: '矩形', value: 'rect' },
      { label: '椭圆', value: 'ellipse' },
      { label: '菱形', value: 'diamond' }
    ];
    
    const specialShapes = {
      'mind': [
        { label: '圆角矩形', value: 'roundRect' },
        { label: '云形', value: 'cloud' }
      ],
      'flow': [
        { label: '圆角矩形', value: 'roundRect' },
        { label: '平行四边形', value: 'parallelogram' }
      ],
      'concept': [
        { label: '六边形', value: 'hexagon' },
        { label: '八边形', value: 'octagon' }
      ]
    };
    
    return [...commonShapes, ...(specialShapes[graphType] || [])];
  };

  const typeOptions = nodeTypeOptions.length > 0 ? nodeTypeOptions : getDefaultNodeTypes();
  const shapeOptions = getShapeOptions();

  // 渲染节点预览
  const renderNodePreview = () => {
    const label = form.getFieldValue('label') || '节点名称';
    const type = form.getFieldValue('type');
    
    let shapeStyle = {};
    switch (nodeShape) {
      case 'rect':
        shapeStyle = {
          width: nodeSize * 1.5,
          height: nodeSize,
          borderRadius: '0'
        };
        break;
      case 'roundRect':
        shapeStyle = {
          width: nodeSize * 1.5,
          height: nodeSize,
          borderRadius: '8px'
        };
        break;
      case 'diamond':
        shapeStyle = {
          width: nodeSize,
          height: nodeSize,
          transform: 'rotate(45deg)',
          marginTop: nodeSize / 4
        };
        break;
      case 'ellipse':
        shapeStyle = {
          width: nodeSize * 1.5,
          height: nodeSize,
          borderRadius: '50%'
        };
        break;
      case 'hexagon':
        // 六边形使用特殊背景
        shapeStyle = {
          width: nodeSize * 1.2,
          height: nodeSize * 1.2,
          clipPath: 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)'
        };
        break;
      case 'cloud':
        // 云形使用特殊边框
        shapeStyle = {
          width: nodeSize * 1.5,
          height: nodeSize,
          borderRadius: '50%',
          boxShadow: `
            ${nodeSize/5}px ${-nodeSize/10}px 0 ${-nodeSize/10}px ${nodeColor},
            ${-nodeSize/5}px ${-nodeSize/10}px 0 ${-nodeSize/10}px ${nodeColor},
            ${nodeSize/3}px ${nodeSize/10}px 0 ${-nodeSize/10}px ${nodeColor},
            ${-nodeSize/3}px ${nodeSize/10}px 0 ${-nodeSize/10}px ${nodeColor}
          `
        };
        break;
      default:
        shapeStyle = {
          width: nodeSize,
          height: nodeSize,
          borderRadius: '50%'
        };
    }

    return (
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        padding: '20px',
        background: '#f5f5f5',
        borderRadius: '6px',
        minHeight: '120px'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div
            style={{
              ...shapeStyle,
              backgroundColor: nodeColor,
              border: '2px solid #fff',
              boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
              margin: '0 auto 12px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            {nodeShape === 'diamond' && (
              <div style={{ transform: 'rotate(-45deg)', fontSize: '10px', color: '#fff' }}>
                {type}
              </div>
            )}
          </div>
          <Text style={{ fontSize: '12px', color: '#666' }}>
            {label}
          </Text>
          <div style={{ fontSize: '10px', color: '#999', marginTop: '4px' }}>
            {type}
          </div>
        </div>
      </div>
    );
  };

  return (
    <Modal
      title={
        <Space>
          <NodeIndexOutlined />
          {mode === 'edit' ? '编辑节点' : '添加节点'}
          {graphStyle?.name && <Text type="secondary">({graphStyle.name})</Text>}
        </Space>
      }
      open={visible}
      onOk={handleSave}
      onCancel={onCancel}
      width={600}
      okText="保存"
      cancelText="取消"
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane 
          tab={
            <span>
              <AppstoreOutlined />
              基本信息
            </span>
          } 
          key="basic"
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              type: typeOptions[0]?.value || 'concept',
              category: ''
            }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="label"
                  label="节点名称"
                  rules={[{ required: true, message: '请输入节点名称' }]}
                >
                  <Input placeholder="请输入节点名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="type"
                  label="节点类型"
                  rules={[{ required: true, message: '请选择节点类型' }]}
                >
                  <Select placeholder="请选择节点类型">
                    {typeOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="description"
              label="节点描述"
            >
              <TextArea 
                rows={3} 
                placeholder="请输入节点描述（可选）" 
              />
            </Form.Item>

            <Form.Item
              name="category"
              label="节点分类"
            >
              <Input placeholder="请输入节点分类（可选）" />
            </Form.Item>
          </Form>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <BgColorsOutlined />
              外观设置
            </span>
          } 
          key="appearance"
        >
          <Card size="small">
            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: '16px' }}>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                    节点颜色
                  </Text>
                  <ColorPicker
                    value={nodeColor}
                    onChange={(color) => setNodeColor(color.toHexString())}
                    showText
                    size="large"
                  />
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                    节点大小: {nodeSize}px
                  </Text>
                  <Slider
                    min={10}
                    max={50}
                    value={nodeSize}
                    onChange={setNodeSize}
                    marks={{
                      10: '小',
                      30: '中',
                      50: '大'
                    }}
                  />
                </div>
              </Col>
            </Row>
            
            <div style={{ marginTop: '16px' }}>
              <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                节点形状
              </Text>
              <Radio.Group 
                value={nodeShape} 
                onChange={(e) => setNodeShape(e.target.value)}
                buttonStyle="solid"
                style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}
              >
                {shapeOptions.map(shape => (
                  <Radio.Button key={shape.value} value={shape.value}>
                    {shape.label}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </div>
          </Card>
          
          {/* 预览 */}
          <Card title="预览效果" size="small" style={{ marginTop: '16px' }}>
            {renderNodePreview()}
          </Card>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <TagsOutlined />
              属性设置
            </span>
          } 
          key="properties"
        >
          <Card size="small">
            <Text type="secondary">
              根据节点类型，您可以添加自定义属性来丰富节点信息。
            </Text>
            
            <Form.List name="properties">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Row key={key} gutter={8} style={{ marginTop: '8px' }}>
                      <Col span={10}>
                        <Form.Item
                          {...restField}
                          name={[name, 'key']}
                          rules={[{ required: true, message: '请输入属性名' }]}
                        >
                          <Input placeholder="属性名" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          {...restField}
                          name={[name, 'value']}
                          rules={[{ required: true, message: '请输入属性值' }]}
                        >
                          <Input placeholder="属性值" />
                        </Form.Item>
                      </Col>
                      <Col span={2}>
                        <Button 
                          type="text" 
                          danger 
                          onClick={() => remove(name)}
                        >
                          删除
                        </Button>
                      </Col>
                    </Row>
                  ))}
                  <Form.Item>
                    <Button 
                      type="dashed" 
                      onClick={() => add()} 
                      block
                      style={{ marginTop: '8px' }}
                    >
                      + 添加属性
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Card>
        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default NodeEditor;